package cc.linker.steplink.crm.merchant.controller;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.utils.CharUtils;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.merchant.service.EnrollService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 国学娃娃报名活动
 */
@RestController
@RequestMapping("/enroll")
public class EnrollController {

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private EnrollService enrollService;

    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 报名活动列表
     * @param session
     * @return
     */
    @GetMapping("/getlist")
    public PageInfo getList(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "keywords", required = false) String keywords,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "isShare", defaultValue = "", required = false) String isShare,
            @RequestParam(value = "reqType", defaultValue = "", required = false) String reqType,
            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;

        Map<String,Object> map = new HashMap<>();
        if(!StringUtils.isEmpty(reqType)){
            map.put("reqType",reqType);
        }
        map.put("orgId", orgId);
        map.put("ifSaler", ifSaler);
        if (ifSaler) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            map.put("customerId", customerId);
            //小b登录时如果选联盟活动，则不展示数据
            if("1".equals(isShare)){
                map.put("isShare","2");
            }
        }else{
            if(!StringUtils.isEmpty(isShare)){
                if("0".equals(isShare)){
                    //自有活动
                    map.put("customerId", orgId);
                }else{
                    //联盟活动
                    map.put("isShare",isShare);
                }
            }else{
                map.put("allEnroll", 1);
            }
        }
        map.put("status", status);
        if(!StringUtils.isEmpty(keywords)){
            map.put("keywords", CharUtils.escapeQueryChars(keywords));
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollService.getList(map));
    }

    @GetMapping("/getenrolllist")
    public PageInfo getEnrollList(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "keywords", required = false) String keywords,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "isShare", defaultValue = "", required = false) String isShare,
            @RequestParam(value = "label", defaultValue = "", required = false) String label,
            HttpServletRequest request
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;

        Map<String,Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("ifSaler", ifSaler);
        if (ifSaler) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            map.put("customerId", customerId);
            //小b登录时如果选联盟活动，则不展示数据
            if("1".equals(isShare)){
                map.put("isShare","2");
            }
        }else{
            if(!StringUtils.isEmpty(isShare)){
                if("0".equals(isShare)){
                    //自有活动
                    map.put("customerId", orgId);
                }else{
                    //联盟活动
                    map.put("isShare",isShare);
                }
            }else{
                map.put("allEnroll", 1);
            }
        }
        map.put("status", status);
        map.put("keywords", keywords);
        map.put("label", label);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollService.getEnrollList(map));
    }

    /**
     * 联盟商品报名活动列表
     * @param session
     * @return
     */
    @GetMapping("/getsharelist")
    public PageInfo getShareList(
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
            @RequestParam(value = "title", defaultValue = "", required = false) String title,
            @RequestParam(value = "name", defaultValue = "", required = false) String name,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,String> param = new HashMap<>();
        param.put("orgId",orgId);
        if(!StringUtils.isEmpty(phone)){
            param.put("phone",phone);
        }
        if(!StringUtils.isEmpty(title)){
            param.put("title",title);
        }
        if(!StringUtils.isEmpty(name)){
            param.put("name",name);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollService.getShareList(param));
    }


 /**
     * 联盟商品报名活动列表
     * @param session
     * @return
     */
    @GetMapping("/allianceShareList")
    public PageInfo allianceShareList(
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
            @RequestParam(value = "title", defaultValue = "", required = false) String title,
            @RequestParam(value = "name", defaultValue = "", required = false) String name,
            @RequestParam(value = "isShare", defaultValue = "-1", required = false) Integer isShare,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> param = new HashMap<>();
        param.put("orgId",orgId);
        if(!StringUtils.isEmpty(phone)){
            param.put("phone",phone);
        }
        if(!StringUtils.isEmpty(title)){
            param.put("title",title);
        }
        if(!StringUtils.isEmpty(name)){
            param.put("name",name);
        }
        param.put("isShare",isShare);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollService.allianceShareList(param));
    }


    /**
     * 封禁/解封活动
     * @param param
     */
    @PostMapping("/banned")
    public void banned(@RequestBody Map<String, String> param, HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId",orgId);
        if(StringUtils.isEmpty(param.get("enrollId"))||StringUtils.isEmpty(param.get("isSeal"))){
            throw GlobalException.build("参数错误");
        }
        enrollService.banned(param);
    }



    /**
     * 添加/移除联盟报名
     * @param param
     */
    @PostMapping("/changetoshare")
    public void changeToShare(@RequestBody Map<String, String> param, HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("enrollId"))||StringUtils.isEmpty(param.get("isShare"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId", userinfo.getOrgId());
        enrollService.changeToShare(param);
    }

    /**
     * 修改报名活动状态
     * @param enrollId
     * @param session
     */
    @GetMapping("/changeenrollstatus")
    public void changeEnrollStatus(String enrollId, HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        Map<String,Object> params = new HashMap<>();
        params.put("orgId",orgId);
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("customerId",customerId);
        }
        //判断是否认证过
        Map<String, Object> merInfo = newMallDao.getMerInfo(params);
        if (merInfo == null || !"2".equals(merInfo.get("checkStatus").toString())) {
            throw GlobalException.build("请先完成商家认证！");
        }
        enrollService.changeEnrollStatus(enrollId, customerId);
    }

    /**
     * 删除活动
     *
     * @param enrollId
     */
    @GetMapping("/delenroll")
    public void delEnroll(String enrollId, HttpServletRequest request   ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        enrollService.delEnroll(enrollId, customerId);
    }

    /**
     * 报名记录列表
     * @param enrollId
     * @param customerName
     * @param optionName
     * @param pageIndex
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("recordlist")
    public PageInfo recordList(
            @RequestParam(value = "enrollId") String enrollId,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "optionName", required = false) String optionName,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            @RequestParam(value = "attrIds",required = false) String attrIds,
            HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("enrollId", enrollId);
        map.put("customerName", customerName);
        map.put("optionName", optionName);
        String[] attrIdatt = attrIds.split(",");
        List<String> attrIdsList = new ArrayList<>();
        if(attrIdatt.length>0){
            Collections.addAll(attrIdsList,attrIdatt);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(enrollService.recordList(map,attrIdsList));
    }

    /**
     * 导出报名记录
     * @param session
     * @param response
     */
    @GetMapping("/exportrecordlist")
    public void exportRecordList(
            @RequestParam(value = "enrollId") String enrollId,
            @RequestParam(value = "customerName", required = false) String customerName,
            @RequestParam(value = "optionName", required = false) String optionName,
            @RequestParam(value = "attrIds",required = false) String attrIds,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("enrollId", enrollId);
        map.put("customerName", customerName);
        map.put("optionName", optionName);
        String[] attrIdatt = attrIds.split(",");
        List<String> attrIdsList = new ArrayList<>();
        if(attrIdatt.length>0){
            Collections.addAll(attrIdsList,attrIdatt);
        }
        enrollService.exportRecordList(map,response,attrIdsList);
    }



    /**
     * 保存活动
     */
    @PostMapping("/saveenroll")
    public void saveEnroll(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String[] check = {"title", "content", "shareContent", "cover", "shareCover", "optionJson", "attrJson"};
        for (String s : check) {
            if (!param.containsKey(s) || StringUtils.isEmpty(param.get(s))) {
                throw GlobalException.build("参数错误");
            }
        }

        if(StringUtils.isEmpty(param.get("startTime"))){
            param.put("startTime",null);
        }
        if(StringUtils.isEmpty(param.get("endTime"))){
            param.put("endTime",null);
        }
        String orgId = userinfo.getOrgId();
        Boolean isSaler = userinfo.getSaler();
        param.put("orgId", orgId);
        if (isSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        enrollService.addEnroll(param);
    }

    @GetMapping("/getinfo")
    public Map<String, Object> getInfo(@RequestParam String enrollId, HttpServletRequest request) {
        if (StringUtils.isEmpty(enrollId)) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, String> param = new HashMap<>(2);
        param.put("orgId", orgId);
        param.put("enrollId", enrollId);
        return enrollService.getInfo(param);
    }

    /**
     * 我的报名
     *
     * @param key       模糊搜索条件
     * @param pageIndex 页码
     * @param pageSize  页大小
     */
    @PostMapping("/myEnroll")
    public PageInfo myEnroll(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Boolean ifSales = userinfo.getSaler();
        String customerId;
        if (ifSales) {
            String adminId = userinfo.getAdminId();
            customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
        } else {
            customerId = userinfo.getOrgId();
        }
        param.put("customerId", customerId);
        return enrollService.myEnroll(param);
    }

    /**
     * 设置推广
     *
     * @param enrollId  报名id
     * @param promotion 0-不推广1-推广
     * @param rebate    反润比例
     */
    @PostMapping("/setEnrollPromotion")
    public void setEnrollPromotion(@RequestBody Map<String, Object> param) {
        enrollService.setEnrollPromotion(param);
    }
}
